package com.ruoyi.yljf.service.impl;


import com.alipay.api.AlipayClient;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.app.models.AlipayTradeAppPayResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.yljf.domain.BalanceDetail;
import com.ruoyi.yljf.domain.PayRecord;
import com.ruoyi.yljf.domain.User;
import com.ruoyi.yljf.domain.dto.AliPayDTO;
import com.ruoyi.yljf.mapper.BalanceDetailMapper;
import com.ruoyi.yljf.mapper.PayRecordMapper;
import com.ruoyi.yljf.mapper.UserMapper;
import com.ruoyi.yljf.service.IAlipayService;
import com.ruoyi.yljf.service.IPayRecordService;
import com.ruoyi.yljf.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName AlipayServiceImpl
 * @Description Alipay支付
 * @Author wangpan
 * @Date 2025/3/17 10:46
 * @Version 1.0
 **/
@Service
@Slf4j
public class AlipayServiceImpl implements IAlipayService {

    @Resource
    private Config config;
    @Resource
    private PayRecordMapper payRecordMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private BalanceDetailMapper balanceDetailMapper;

    @Override
    public HashMap<String, String> aliPayByApp(AliPayDTO aliPayDTO) throws Exception {
        // 1. 设置参数（全局只需设置一次）
        HashMap<String, String> resMap = new HashMap<>();
        Factory.setOptions(config);
        try {
            String orderNo = this.createOrderNum(aliPayDTO);   //订单号
            PayRecord payRecord = new PayRecord( null,orderNo, aliPayDTO.getUserId(),"ali",aliPayDTO.getTotalAmount(),new Date(),"充值",0);
            this.payRecordMapper.insert(payRecord);  //新增支付记录
            // 2. 发起API调用（以创建当面付收款二维码为例）
            AlipayTradeAppPayResponse response = Factory.Payment.App()
                    .pay(aliPayDTO.getSubject(),  //订单描述
                            orderNo, //交易单号
                            String.valueOf(aliPayDTO.getTotalAmount())); //交易金额
            // 3. 处理响应或异常
            if (ResponseChecker.success(response)) {
                System.out.println("调用成功");
                log.info("支付宝扫码支付二维码：{}", response.getBody());
                resMap.put("orderInfo", response.getBody());
            } else {
                System.err.println("调用失败，原因：" + response);
                resMap.put("error_msg", response.getBody()
                );
            }
        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
        return resMap;
    }

    @Override
    public String doAliPayCallBack(HttpServletRequest request) throws Exception {
        String result = "failure";
        Map<String, String> params = getRequestParam(request);
        if (!Factory.Payment.Common().verifyNotify(params)) {
            log.info("支付结果校验失败");
        }
        String outTradeNo = params.get("out_trade_no");
        String tradeStatus = params.get("trade_status");

        if (tradeStatus .equals("TRADE_SUCCESS")) {
            log.info("支付成功，订单号:{}", outTradeNo );

            result = "success";
            updateInfo(outTradeNo);     //更新部分信息
            //更新保存线上支付的订单信息,修改用户余额

            //updatePayRecord1(params, outTradeNo );
        } else {
            log.info("支付失败，订单号:{}", outTradeNo );
            //更新保存的订单信息
            //updatePayRecord2(params, outTradeNo );
        }
        return result;

    }

    public String createOrderNum(AliPayDTO aliPayDTO){
        DateTimeFormatter ofPattern =DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
        String localDate = LocalDateTime.now().format(ofPattern);
        String randomNumeric = RandomStringUtils.randomNumeric(3);
        return localDate + randomNumeric + aliPayDTO.getUserId().toString();
    }

    //处理得到的参数
    private Map<String, String> getRequestParam(final HttpServletRequest request) {
        Map<String, String> res = new HashMap<>();
        Enumeration<?> temp = request.getParameterNames();
        while (temp.hasMoreElements()) {
            String en = (String) temp.nextElement();
            String value = request.getParameter(en);
            res.put(en, value);
        }
        return res;
    }

    //事务处理订单成功之后的操作
    @Transactional
    public void updateInfo(String outTradeNo) {
        PayRecord record = payRecordMapper.selectOne(
                new LambdaQueryWrapper<PayRecord>()
                        .eq(PayRecord::getOrderNo, outTradeNo));
        record.setStatu(1);
        payRecordMapper.updateById(record);     //修改订单状态
        //修改用户余额
        userMapper.update(null,
                new LambdaUpdateWrapper<User>().
                        eq(User::getUserId, record.getUserId())
                        .setSql("balance = balance + "+record.getAmount()));
        log.info("充值日志 - 订单号：{}, 用户ID：{}, 金额：{}, 时间：{}",
                outTradeNo,
                record.getUserId(),
                record.getAmount(),
                LocalDateTime.now());
        //增加充值记录
        balanceDetailMapper.insert(
                new BalanceDetail(null,record.getUserId(),"充值",new Date(),record.getAmount().toString())
        );
    }

//    public static void main(String[] args) throws AlipayApiException {
//        // 初始化SDK
//        AlipayClient alipayClient = new DefaultAlipayClient(getAlipayConfig());
//
//        // 构造请求参数以调用接口
//        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
//        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
//
//        // 设置商户订单号
//        model.setOutTradeNo("70501111111S001111119");
//
//        // 设置订单总金额
//        model.setTotalAmount("9.00");
//
//        // 设置订单标题
//        model.setSubject("大乐透");
//
//        // 设置产品码
//        model.setProductCode("QUICK_MSECURITY_PAY");
//
//        // 设置订单包含的商品列表信息
//        List<GoodsDetail> goodsDetail = new ArrayList<GoodsDetail>();
//        GoodsDetail goodsDetail0 = new GoodsDetail();
//        goodsDetail0.setGoodsName("ipad");
//        goodsDetail0.setAlipayGoodsId("20010001");
//        goodsDetail0.setQuantity(1L);
//        goodsDetail0.setPrice("2000");
//        goodsDetail0.setGoodsId("apple-01");
//        goodsDetail0.setGoodsCategory("34543238");
//        goodsDetail0.setCategoriesTree("124868003|126232002|126252004");
//        goodsDetail0.setShowUrl("http://www.alipay.com/xxx.jpg");
//        goodsDetail.add(goodsDetail0);
//        model.setGoodsDetail(goodsDetail);
//
//        // 设置订单绝对超时时间
//        model.setTimeExpire("2016-12-31 10:05:00");
//
//        // 设置业务扩展参数
//        ExtendParams extendParams = new ExtendParams();
//        extendParams.setSysServiceProviderId("2088511833207846");
//        extendParams.setHbFqSellerPercent("100");
//        extendParams.setHbFqNum("3");
//        extendParams.setIndustryRefluxInfo("{\"scene_code\":\"metro_tradeorder\",\"channel\":\"xxxx\",\"scene_data\":{\"asset_name\":\"ALIPAY\"}}");
//        extendParams.setCardType("S0JP0000");
//        model.setExtendParams(extendParams);
//
//        // 设置公用回传参数
//        model.setPassbackParams("merchantBizType%3d3C%26merchantBizNo%3d2016010101111");
//
//        // 设置商户的原始订单号
//        model.setMerchantOrderNo("20161008001");
//
//        // 设置外部指定买家
//        ExtUserInfo extUserInfo = new ExtUserInfo();
//        extUserInfo.setCertType("IDENTITY_CARD");
//        extUserInfo.setCertNo("362334768769238881");
//        extUserInfo.setName("李明");
//        extUserInfo.setMobile("16587658765");
//        extUserInfo.setMinAge("18");
//        extUserInfo.setNeedCheckInfo("F");
//        model.setExtUserInfo(extUserInfo);
//
//        // 设置通知参数选项
//        List<String> queryOptions = new ArrayList<String>();
//        queryOptions.add("hyb_amount");
//        queryOptions.add("enterprise_pay_info");
//        model.setQueryOptions(queryOptions);
//
//        request.setBizModel(model);
//        // 第三方代调用模式下请设置app_auth_token
//        // request.putOtherTextParam("app_auth_token", "<-- 请填写应用授权令牌 -->");
//
//        AlipayTradeAppPayResponse response = alipayClient.sdkExecute(request);
//        String orderStr = response.getBody();
//        System.out.println(orderStr);
//
//        if (response.isSuccess()) {
//            System.out.println("调用成功");
//        } else {
//            System.out.println("调用失败");
//            // sdk版本是"4.38.0.ALL"及以上,可以参考下面的示例获取诊断链接
//            // String diagnosisUrl = DiagnosisUtils.getDiagnosisUrl(response);
//            // System.out.println(diagnosisUrl);
//        }
//    }
//
//    private static AlipayConfig getAlipayConfig() {
//        String privateKey  =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qQF4KQEsmd9BYgywKBgCq6Jd2vI0Zg/ljKVv8gZCuqWuHuMm1I8mpJr7gWTjp2m9rOEW2kiQRDrZjCECAFpegEdbOaq6tIx53/dPCwlUoQ11IUD9+a7wFfnDYN0kUewT9MI0IPHeJBg/tA5Z+cuqCK4QZPlXNRF8WvyA2klQdlp0+twnm9SAh1eaJLrG7hAoGALmHjOyXeghU1yDKd460EYtUA/roo/2H27RnN8ko8SjGh+sw8mppSJa59N5CscdTUTqfTsr0DFghWKkwOS31nRczpa3f+uskP8TF7oxWFeQiMsK4jFB+uF6m8+LWieXmJcPR8JaOsqmtTUVwep5dqdzeHlipLN0emF+tkc3qR+4ECgYBNH37YVYktcsM/80FDut2wrvuDAVsjAO4qbaYCfN2duzqPJkBrz2Xvv2ITao7f+VqG2HNdmqgn8fdaBqQnpUOSbNNVrqGOHJ1Z8F2nKF7dZCyExmZgYoLaDwvrbnuunWnxJWjprgyA9dfUqUhGqsKOM61pWSEeC+fZMXFmSveOzQ==";
//        String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoI4FaVwt+bX/AUFQmcZFQZtXgTRVIAqcji1jnTnmGAGFmfl3mqjCoPQJ7OyPvD4r5SHJ3MYACEn0mlZOX+QNFqvqdlZRtS2ZcIM/hCPAM2V1jaCJ/Eh1TEZH0yJhTftETSkECbfmtdHVavCVKq/6QKHU4+K0UQ1pRR74vBPjwTFdM3n93MX1SF6y7Amavvw7PbJwnY+sAamKk0GCR/KnehpuoD4jR2qVtpTiaF/5LgMqJkepfFbpvhQzzbgdYPGE5ES+rGwY6mvesrlgHa/e/24tYHlN3mhjhWh7bdqbtQEgBQX1JCetY8NIEmIQzqBuYJdlTMUFkPsdHHW4vtrOgwIDAQAB";
//        AlipayConfig alipayConfig = new AlipayConfig();
//        alipayConfig.setServerUrl("https://openapi-sandbox.dl.alipaydev.com/gateway.do");
//        alipayConfig.setAppId("2021000146660134");
//        alipayConfig.setPrivateKey(privateKey);
//        alipayConfig.setFormat("json");
//        alipayConfig.setAlipayPublicKey(alipayPublicKey);
//        alipayConfig.setCharset("UTF-8");
//        alipayConfig.setSignType("RSA2");
//        return alipayConfig;
//    }




}
